package api

import (
	"moss/meta"
	"moss/proto"
	"moss/status"
	"strings"
)

func PutBucketReferer(requestId string, accessKeyId string, bucketName string, xmlDoc proto.RefererConfiguration) status.Status {
	if !validIdentifier(bucketName) {
		return status.InvalidBucketName
	}
	bucketMeta, ok := meta.GetBucketInfo(bucketName)
	if !ok {
		return status.NoSuchBucket
	}

	if bucketMeta.OwnerAccessKeyId != accessKeyId {
		return status.AccessDenied
	}

	if !xmlDoc.AllowEmptyReferer && len(xmlDoc.RefererList.Referer) == 0 {
		return status.InvalidArgument
	}

	refererList := strings.Join(xmlDoc.RefererList.Referer, ",")
	meta.SetRefererList(bucketName, accessKeyId, refererList, xmlDoc.AllowEmptyReferer)
	return status.Success
}

func GetBucketReferer(requestId string, accessKeyId string, bucketName string) (*proto.RefererConfiguration, status.Status) {
	if !validIdentifier(bucketName) {
		return nil, status.InvalidBucketName
	}

	bucketMeta, ok := meta.GetBucketInfo(bucketName)
	if !ok {
		return nil, status.NoSuchBucket
	}

	if bucketMeta.OwnerAccessKeyId != accessKeyId {
		return nil, status.AccessDenied
	}

	var xmlDoc proto.RefererConfiguration
	refererList, ok := meta.GetBucketReferer(bucketName)
	if !ok {
		xmlDoc.AllowEmptyReferer = true
		return &xmlDoc, status.Success
	}

	xmlDoc.AllowEmptyReferer = refererList.AllowEmptyReferer
	refererArray := strings.Split(refererList.Referer, ",")
	for _, entry := range refererArray {
		xmlDoc.RefererList.Referer = append(xmlDoc.RefererList.Referer, entry)
	}

	return &xmlDoc, status.Success
}
